package com.app.signing.utils;

import java.util.Timer;
import java.util.TimerTask;

/**
 * @author wangpeifeng
 * @date 2018/05/08 14:16
 */
public class TimerUtil {

    private Timer timer;
    private TimerTask timerTask;
    private long startTime;
    private TimeCallback timeCallback;

    public TimerUtil(long startTime, TimeCallback timeCallback) {
        this.startTime = startTime;
        this.timeCallback = timeCallback;
        timer = new Timer();
    }

    public void start() {
        timerTask = new Task(startTime, timeCallback);
        timer.schedule(timerTask, 0, 1000);
    }

    public void stop() {
        if (!timerTask.cancel()) {
            timerTask.cancel();
            timer.cancel();
        }
    }

    public static class Task extends TimerTask {

        private long startTime;
        private TimeCallback timeCallback;

        public Task(long startTime, TimeCallback timeCallback) {
            this.timeCallback = timeCallback;
            this.startTime = System.currentTimeMillis() - startTime;
        }

        @Override
        public void run() {
            startTime += 1000;
            timeCallback.timeChange(formatTime(startTime));
        }

        private String formatTime(long totalTime) {
            long hour = 0;
            long minute = 0;
            long second;
            second = totalTime / 1000;
            if (totalTime <= 1000 && totalTime > 0) {
                second = 1;
            }
            if (second > 60) {
                minute = second / 60;
                second = second % 60;
            }
            if (minute > 60) {
                hour = minute / 60;
                minute = minute % 60;
            }
            // 转换时分秒 00:00:00
            return (hour >= 10 ? hour : "0" + hour)
                    + ":"
                    + (minute >= 10 ? minute : "0" + minute)
                    + ":"
                    + (second >= 10 ? second : "0" + second);
        }
    }

    public interface TimeCallback {

        void timeChange(String time);
    }
}
